package com.example.video.common.config.RabbitMQ;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 创建视频延迟消息队列配置
 * <p/>
 *
 * @author : yj
 */
@Configuration
public class CreateVideoDelay {

    // 待确定队列
    private static final String WAITED_CREATE_VIDEO_QUEUE = "WAITED_CREATE_VIDEO_QUEUE";

    // 删除视频队列
    public static final String DEL_VIDEO_QUEUE = "DEL_VIDEO_QUEUE";

    // 死信交换机
    public static final String DL_EXCHANGE = "VIDEO_DL_EXCHANGE";

    // 延迟等待队列交换机标识
    public static final String WAITED_KEY = "VIDEO_WAITED_KEY";

    // 删除队列交换机标识
    public static final String DEL_KEY = "VIDEO_DEL_KEY";

    //过期时间
    static final int OUT_TIME = 60000;

    /**
     * 死信队列跟交换机类型没有关系 不一定为directExchange  不影响该类型交换机的特性.
     *
     * @return the exchange
     */
    @Bean
    public Exchange deadLetterExchange() {
        return ExchangeBuilder.directExchange(DL_EXCHANGE).durable(true).build();
    }

    /**
     * 声明一个死信队列.
     * x-dead-letter-exchange   对应  死信交换机
     * x-dead-letter-routing-key  对应 死信队列
     *
     * @return the queue
     */
    @Bean
    public Queue deadLetterQueue() {
        Map<String, Object> args = new HashMap<>(3);
//       x-dead-letter-exchange    声明  死信交换机
        args.put("x-dead-letter-exchange", DL_EXCHANGE);
//       x-dead-letter-routing-key    声明 死信路由键
        args.put("x-dead-letter-routing-key", DEL_KEY);
        args.put("x-message-ttl", OUT_TIME);
        return QueueBuilder.durable(WAITED_CREATE_VIDEO_QUEUE).withArguments(args).build();
    }

    /**
     * 定义死信队列转发队列.
     *
     * @return the queue
     */
    @Bean
    public Queue redirectQueue() {
        return QueueBuilder.durable(DEL_VIDEO_QUEUE).build();
    }

    /**
     * 死信路由通过 DL_KEY 绑定键绑定到死信队列上.
     *
     * @return the binding
     */
    @Bean
    public Binding deadLetterBinding() {
        return new Binding(WAITED_CREATE_VIDEO_QUEUE, Binding.DestinationType.QUEUE, DL_EXCHANGE, WAITED_KEY, null);
    }

    /**
     * @return the binding
     */
    @Bean
    public Binding redirectBinding() {
        return new Binding(DEL_VIDEO_QUEUE, Binding.DestinationType.QUEUE, DL_EXCHANGE, DEL_KEY, null);
    }

}